<template>
  <div>
      <van-nav-bar
  title="黑马-头条-登陆"/>
<van-form @submit="onSubmit">
  <van-field
    v-model="fromLogin.mobile"
    label="手机号"
    placeholder="请输入手机号"
    required
    :rules="[
      {
        pattern:/^1[3-9]\d{9}$/,
        tigger:'onChange',
        required: true,
        message: '请填写手机号'
     }
    ]"
  />
  <van-field
    v-model="fromLogin.code"
    type="password"
    required
    label="密码"
    placeholder="密码"
    :rules="[
      {
        pattern:/^\d{6}$/,
        tigger:'onChange',
        required: true,
         message: '请填写密码'
      }
    ]"
  />
  <div style="margin: 16px;">
    <van-button
    round
    block
    type="info"
    :loading="toggle"
    :disabled="toggle"
    loading-text="登陆中..."
    native-type="submit"
    >登陆</van-button>
  </div>
</van-form>
 </div>
</template>

<script>
import { loginAPI } from '@/api'
// 自己封装的通知插件
import { MyNotify } from '@/utils/Notify'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      fromLogin: {
        mobile: '17610301099', // 手机号
        code: '246810' // 后台只能用着个密码
      },
      toggle: false // 按钮加载状态和禁用状态

    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    async onSubmit () {
      try {
        this.toggle = true // 按钮切换
        const res = await loginAPI(this.fromLogin)
        this.setToken(res.data.data.token)
        this.setRefreshToken(res.data.data.refresh_token)
        console.log(res)
        this.toggle = false
        MyNotify({ type: 'success', message: '登陆成功' })
        // this.$router.push({
        //   path: '/layout'
        // })

        // 如果状态码为401退出的登陆, 则返回之前浏览的页面
        if (this.$route.query.code === '401') {
          this.$router.back()
        } else { // 否则进入首页
          this.$router.replace({
            path: '/layout'
          })
        }
      } catch (err) {
        MyNotify({ type: 'warning', message: '登陆失败' })
        // 如果登陆失败了按钮也得放开
        this.toggle = false
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>
// .van-nav-bar__content{
//     background-color: #007bff;
// }
// 组件内的标签不会被scoped影响,不会添加data-v属性

// /* /deep/ 后代选择器 就是把data-v-hash值选择器写到类名的前面 */
// /deep/ .van-nav-bar__title{
//    color: white;
// }
</style>
